package tests {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.system.System;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.getTimer;

	/**
	 * @author Charlie MacIsaac
	 */
	
	public class Profiler extends Sprite {
		// PROPERTIES =============================================================================
		private const UPDATE_DELAY : uint = 500;
		
		private var _memoryDisplay : TextField;
		private var _FPSDisplay : TextField;
		
		private var _frames : uint;
		private var _timeUpdated : uint;
		
		// GETTERS + SETTERS ======================================================================
		// CONSTRUCTOR ============================================================================
		public function Profiler() {
			var tint : Sprite = new Sprite();
			tint.graphics.beginFill(0xFFFFFF);
			tint.graphics.drawRect(0, 0, 95, 16);
			tint.graphics.endFill();
			tint.alpha = 0.5;
			addChild(tint);
			
			var format : TextFormat = new TextFormat("Tahoma", 10, 0x000000, true);
			_memoryDisplay = new TextField();
			_memoryDisplay.width = 40;
			_memoryDisplay.defaultTextFormat = format
			_memoryDisplay.selectable = false;
			addChild(_memoryDisplay);
			
			_FPSDisplay = new TextField();
			_FPSDisplay.width = 60;
			_FPSDisplay.defaultTextFormat = format;
			_FPSDisplay.selectable = false;
			_FPSDisplay.x = _memoryDisplay.width + 5;
			addChild(_FPSDisplay);
			
			addEventListener(Event.ADDED_TO_STAGE, enable, false, 0, true);
			addEventListener(Event.REMOVED_FROM_STAGE, disable, false, 0, true);
		}
		
		// PUBLIC =================================================================================
		// PRIVATE ================================================================================
		// LISTENERS ==============================================================================
		private function enable(e : Event) : void {
			addEventListener(Event.ENTER_FRAME, measureTimeBetweenFrames, false, 0, true);
			_timeUpdated = getTimer();
		}
		
		private function disable(e : Event) : void {
			removeEventListener(Event.ENTER_FRAME, measureTimeBetweenFrames, false);
		}
		
		private function measureTimeBetweenFrames(e : Event) : void {
			var now : uint = getTimer();
			var timeSinceLastUpdate : uint = now - _timeUpdated;
			_frames++;
			
			if (timeSinceLastUpdate >= UPDATE_DELAY) {
				_memoryDisplay.text = uint(System.totalMemory * 0.000000953674316) + " MB";
				_FPSDisplay.text = "FPS : " + uint(_frames / timeSinceLastUpdate * 1000);
				_frames = 0;
				_timeUpdated = now;
			}
		}
	}
}